package com.cangshi.service;


import com.cangshi.dao.BillMapper;
import com.cangshi.dao.UserMapper;
import com.cangshi.entity.Bill;
import com.cangshi.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Eoly on 2017/1/16.
 */
@Service("BillService")
public class BillServiceImpl implements BillService {

    @Autowired
    BillMapper billMapper;

    @Autowired
    UserMapper userMapper;

    public List<Bill> findByUserId(Integer userId) {
        return billMapper.selectByUserId(userId);
    }

    public Integer addBill(Bill bill) {
        //获取用户对象用以查找余额
        User checkUser = userMapper.selectByPrimaryKey(bill.getUserId());

        if (checkUser == null) {
            return 702;
        }

        Double balance = checkUser.getUserBalance();

        balance += bill.getBillChangeValue() * bill.getBillChangeType();

        if (bill.getBillChangeType() == -1 && balance < 0) {
            return 700;
        }

        bill.setBillBalance(balance);

        //实例化一个用户对象用以修改余额
        User resultUser = new User();
        resultUser.setUserId(bill.getUserId());
        resultUser.setUserBalance(balance);

        //修改余额以及添加账单操作
        Integer result = userMapper.updateByPrimaryKeySelective(resultUser);
        if (result == 1) {
            result = billMapper.insertSelective(bill);
        }

        return result;
    }
}
